/*
 * Created by Jaren at 2022/01/29 16:53
 */
import 'dart:io';
import 'package:get/get.dart';
import 'package:inmotion_protocol/common/media_file_upload_manager.dart';
import 'package:inmotion_protocol_example/module/base/base.dart';
import 'package:inmotion_protocol/inmotion_protocol.dart';
import 'package:inmotion_protocol/util/log.dart';
import 'package:path_provider/path_provider.dart';

class AudioPkgController extends BaseController {
  SoundFileUploadManager? audioFileUploadManager;

  RxString updateStatus = RxString("IDLE");

  InMotionProtocol protocol = Get.find(tag: 'protocol');

  @override
  void init() {
    audioFileUploadManager = protocol.createSoundFileUploadManager();

    prepareSoundPackConfig(45);
  }

  Future prepareSoundPackConfig(id) {
    return getApplicationDocumentsDirectory().then((dir) {
      MediaUploadConfig config = audioFileUploadManager!.createSoundPackConfig(File(dir.path + "/audio/pkg/$id.rmf"), id);
      audioFileUploadManager!.config(config);
      return audioFileUploadManager;
    });
  }

  Future prepareSoundItemConfig(id) {
    return getApplicationDocumentsDirectory().then((dir) {
      MediaUploadConfig config = audioFileUploadManager!.createSoundItemConfig(File(dir.path + "/audio/item/$id.rmf"), id);
      audioFileUploadManager!.config(config);
      return audioFileUploadManager;
    });
  }

  void startUpload() {
    audioFileUploadManager!.start().listen((event) {
      LogUtils.d("UploadEvent, ${event.toString()}, desc: ${getUpdateStatusDesc(event)}");
      switch (event.type) {
        case UploadEvent.typeCanceled:
          updateStatus.value = "已取消";
          break;
        case UploadEvent.typeCheckStorageCapacity:
          updateStatus.value = "正在准备";
          break;
        case UploadEvent.typeFileOpened:
          updateStatus.value = "正在准备";
          break;
        case UploadEvent.typeFileTransferring:
          event as FileTransferringEvent;
          updateStatus.value =
              "文件传输中，progress: ${event.progress()}, total: ${event.total()}, aveSpeed: ${event.aveSpeed()}, rtSpeed: ${event.rtSpeed()}, remain seconds: ${event.remainSeconds()}, cost seconds: ${event.costSeconds()}";
          break;
        case UploadEvent.typeFileChecked:
          updateStatus.value = "正在校验文件";
          break;
        case UploadEvent.typeFileClosed:
          updateStatus.value = "文件已关闭";
          break;
        case UploadEvent.typeFinished:
          updateStatus.value = "已完成";
//                    protocol.setSoundPackId(10);
          break;
      }
    }).onError((error) {
      updateStatus.value = "Caught unknown error, $error";
      LogUtils.d('Caught error in audio pack upload page, $error');
      if (error is MediaFileUploadError) {
        if (error.isStorageCapacityNotEnough()) {
          // 剩余空间不足
        } else if (error.isNotNowError()) {
          // 当前状态不允许此操作
          LogUtils.d('Motor is working!!!');
          updateStatus.value = "Motor is working!!!";
        } else {
          LogUtils.d('code: ' + error.formatErrorCode(''));
          updateStatus.value = "code: " + error.formatErrorCode('');
        }
      }
    });
  }

  void cancelUpload() {
    audioFileUploadManager!.cancel();
  }

  String getUpdateStatusDesc(UploadEvent event) {
    return event.toString();
  }
}

class InvalidDeviceStateException implements Exception {
  factory InvalidDeviceStateException([var message]) => InvalidDeviceStateException(message);
}
